
#include <string.h>
#include <iostream>
using std::cout;
using std::endl;


class Computer {
public:
    Computer()
    : _brand(nullptr)
    , _price(0)
    { cout << "Computer()" << endl; }

    Computer(const char * brand, double price)
    : _brand(new char[strlen(brand) + 1]())
    , _price(price)
    {
        cout << "Computer(const char*, double)" << endl;
        strcpy(_brand, brand);
        _totalPrice += _price;
    }

    
    Computer(const Computer & rhs)
    : _brand(new char[strlen(rhs._brand) + 1]())
    , _price(rhs._price)
    {   
        cout << "Computer(const Computer&)" << endl;    
        strcpy(_brand, rhs._brand);//深拷贝
    }

    Computer & operator=(const Computer & rhs)
    {
        cout << "Computer & operator=(const Computer&)" << endl;
        if(this != &rhs) {//1. 自复制
            delete [] _brand;//2. 回收左操作数的空间
            _brand = new char[strlen(rhs._brand) + 1]();
            strcpy(_brand, rhs._brand);//3. 深拷贝

            _price = rhs._price;
        }
        return *this;//4. return *this
    }

    void print() 
    {
        if(_brand) {
            cout << "brand:" << this->_brand << endl;
            cout << "price:" << this->_price << endl;
        }
    }

    //静态成员函数没有隐含的this指针
    static void printTotalPrice()
    {   
        //this->print();
        //cout << "price:" << this->_price << endl;
        cout << "total price:" << _totalPrice << endl;
    }

    ~Computer()
    {
        cout << "~Computer()" << endl;
        if(_brand) {
            delete [] _brand;
            _brand = nullptr;
        }
    }

    

private:
    char * _brand;
    double _price;
    //全局静态区
    //编译时可以直接获取该值
    static constexpr double _dm = 0;
    static const int _iz = 0;

    static double _totalPrice;
};


//在类之外进行初始化, 是一个特殊的存在
double Computer::_totalPrice = 0;

void test0()
{
    cout << "sizeof(Computer):" << sizeof(Computer) << endl;
    Computer pc1("Huawei matebook", 7777);  
    cout << "pc1:";
    pc1.print();
    //pc1.printTotalPrice();
    //静态成员函数不需要通过对象调用
    //可以直接通过类名进行调用
    Computer::printTotalPrice();

    Computer pc2("Xiaomi", 8888);
    cout << "\npc2:";
    pc2.print();
    //pc2.printTotalPrice();
    Computer::printTotalPrice();
    pc1.printTotalPrice();

    //cout << pc1._totalPrice << endl;

}


int main()
{
    test0();
    return 0;
}

